//
//  SRClassWorkListViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/7/20.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRClassHomeWorkListViewController.h"

#import <MJRefresh/MJRefresh.h>
#import "SRClassConstants.h"
#import "SRPersonalServices.h"

#import "SRClassHomeworkListTableViewCell.h"
#import "SRClassHomeWorkDetailViewController.h"
#import "SRSchoolClassServices.h"
#import "SRClassIdentySelectView.h"
#import "FZEnglishLevelSelectView.h"

#import "SRGradeItemModel.h"

#import "SRCreateClassViewController.h"
#import "SRAddClassViewController.h"
#import "SRClassDetailViewController.h"

#import "SRAlbumListViewController.h"
#import "SRGradeListViewController.h"

#import "FZMCCacheManager.h"
#import "SRSchoolClassListModel.h"
#import "SRSpeakingDatabaseManager.h"

#import "SRBookCatalogueModel.h"
#import "SRBookRootModel.h"
#import "SRBookPageModel.h"
#import "SRSpeakingTestViewController.h"
#import "SRCommonConstants.h"
#import "SRBookCatalogueSectionHeaderView.h"
#import "SRClassHomeworkStudentFinishViewController.h"

#import "SRHomewokPictureViewController.h"
#import "SRHomewokRecordViewController.h"
#import "SRAddToSchoolViewController.h"
#import "SRHomeworkAudioViewController.h"

#import "SRHomeworkTitleView.h"
#import "SRClassInfoHeaderView.h"
#import "SRClassMemberListViewController.h"


NSString *const kAlbumSectionDefineKey = @"displayTimeString";


@interface SRClassHomeWorkListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) SRClassIdentySelectView *idtentySelectView;

@property (strong, nonatomic) UIView *levelBackgroundView;
@property (strong, nonatomic) FZEnglishLevelSelectView *levelSelectView;
@property (strong, nonatomic) SRClassInfoHeaderView *infoHeaderView;


@property (strong, nonatomic) SRHomeworkTitleView *titleView;
@property (strong, nonatomic) UILabel *areaLabel;
@property (strong, nonatomic) UIImageView *arrowImageView;


@property (strong, nonatomic) NSMutableArray *items;
@property (assign, nonatomic) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *sectionArray;

@property (strong, nonatomic) NSArray *classArray;//班级列表
@property (strong, nonatomic) NSString *groupID;//当前班级id

@property (strong, nonatomic) UIButton *rightButton;
@property (strong, nonatomic) FZDirectionButton *addClassButton;
@property (strong, nonatomic) UIButton *classDetailButton;


@property (strong, nonatomic) SRSchoolClassListModel *currentClassModel;
@property (assign, nonatomic) BOOL isEditStatus;
@property (strong, nonatomic) SRWorkListItemModel *selectedModel;


@end

@implementation SRClassHomeWorkListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    
//    self.title = @"我的班级";
    [self setupData];
    [self setupView];
    [self setupTitleView];
    
    [self setupNavigationItem];

    if (self.userType == SRSchoolClassUserTypeNone) {
            //显示身份选择view
    } else {
        [self showLoadingViewWithCompletedBlock:nil];
        [self queryClassListData];
        
    }
    
    WEAKSELF
    self.loadingView.clickButtonBlock = ^(id sender) {
        if (weakSelf.loadingView.status == FZLoadingViewStatusEmpty) {
            if (weakSelf.userType == SRSchoolClassUserTypeStudent) {
                [weakSelf showAddClassVC];
            } else {
                [weakSelf showCreateClassVC];
            }
        } else {
            [weakSelf queryHomeworkDataFirst];
        }
    };
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(schoolUserTypeDidChangeNotification:) name:kSRSchoolUserTypeDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(schoolUserTypeDidChangeNotification:) name:kSRCreateClassDidSuccessNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AddTaskDidSuccessNotification:) name:kSRAddTaskDidSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AddClassDidSuccessNotification:) name:kSRAddClassDidSuccessNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginDidChangeNotification:) name:SRUserLoginDidChangeNotification object:nil];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self checkSelectIdenty];
    
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	
	if (self.isEditStatus) {
		self.isEditStatus = NO;
		[self.tableView reloadData];
	}
}

- (void)checkSelectIdenty {
    if (self.userType == SRSchoolClassUserTypeNone) {
            //显示身份选择view
        self.idtentySelectView.hidden = NO;
        [self.view bringSubviewToFront:self.idtentySelectView];
        [self.idtentySelectView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    } else {

        if (self.userType != [SRLoginUser schoolIdentity]) {
            self.userType = [SRLoginUser schoolIdentity];
            
            [self updateNaviButtonsHiddenStatus];
            [self showLoadingViewWithCompletedBlock:nil];
            [self queryClassListData];
        }
    }
}

#pragma mark - setup

- (void)setupData {
    self.pageIndex = 0;
    self.items = [@[] mutableCopy];
    self.sectionArray = [@[] mutableCopy];

    self.userType = [SRLoginUser schoolIdentity];
}

- (void)setupView {
    
    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 140;
	self.tableView.estimatedSectionFooterHeight = 0;
	self.tableView.estimatedSectionHeaderHeight = 0;
	
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRClassHomeworkListTableViewCell bundle:nil] forCellReuseIdentifier:kSRClassHomeworkListTableViewCell];
    [self.tableView registerClass:[SRBookCatalogueSectionHeaderView class] forHeaderFooterViewReuseIdentifier:kSRBookCatalogueSectionHeaderView];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
	
    self.view.backgroundColor = self.tableView.backgroundColor = css.color_2;
    
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        weakSelf.pageIndex = 0;
        [weakSelf queryHomeworkData];
    }];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf queryHomeworkData];
    }];
	
	
	self.infoHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"SRClassInfoHeaderView" owner:nil options:nil] firstObject];
	[self.view addSubview:self.infoHeaderView];
	
	self.infoHeaderView.showMessageBlock = ^(NSString *message) {
		[weakSelf showHUDErrorMessage:message];
	};
	
	self.infoHeaderView.showMemberBlock = ^{
		[weakSelf onShowMemberListButton:nil];
	};
	
	[self.infoHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.leading.trailing.top.equalTo(self.view);
		make.height.mas_equalTo(125);
	}];
	
	[self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.top.equalTo(self.infoHeaderView.mas_bottom);
		make.leading.trailing.bottom.equalTo(self.view);
	}];
}

- (SRClassIdentySelectView *)idtentySelectView {
    if (!_idtentySelectView) {
        _idtentySelectView = [[[NSBundle mainBundle] loadNibNamed:@"SRClassIdentySelectView" owner:nil options:nil] firstObject];
        WEAKSELF
        _idtentySelectView.touchIdentyBlock = ^(BOOL isTeacher) {
            [weakSelf onTouchSelectIdenty:isTeacher];
        };
        
        _idtentySelectView.frame = self.view.bounds;
        
        [self.view addSubview:_idtentySelectView];
    }

    return _idtentySelectView;
}


- (void)setupTitleView {
//    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
        //    CGFloat subtitleHeight = 15;
    CGFloat navigationHeiht = 44;
    SRHomeworkTitleView *titleView = [[SRHomeworkTitleView alloc] initWithFrame:CGRectMake(0, 0, 220, navigationHeiht)];
        //    titleView.backgroundColor = [UIColor redColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 0, 60, navigationHeiht )];
    titleLabel.text = @"我的班级";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:17.f];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.areaLabel = titleLabel;
    WEAKSELF
    [self.areaLabel addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf onleftChangeLevelButton:nil];
    }];
    
    UIImageView *arrowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"downWardTriangle"]];
    arrowImageView.contentMode = UIViewContentModeScaleAspectFit;
    arrowImageView.userInteractionEnabled = YES;
    self.arrowImageView = arrowImageView;
    
    [self.arrowImageView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf onleftChangeLevelButton:nil];

    }];
//    [titleView addSubview:titleLabel];
    [titleView addSubview:self.areaLabel];
    [titleView addSubview:arrowImageView];
    titleView.frame = CGRectMake(0, 0, 100, 44);
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.backgroundColor = [UIColor whiteColor ];
//    [titleView addSubview:btn];
//
//    [btn addTarget:self action:@selector(onleftChangeLevelButton:) forControlEvents:UIControlEventTouchUpInside];
//
//    titleView.backgroundColor = [UIColor lightGrayColor];
//    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
////        make.leading.trailing.bottom.top.equalTo(titleView);
//        make.leading.equalTo(self.areaLabel.mas_leading);
//        make.trailing.equalTo(self.arrowImageView.mas_trailing);
//        make.height.mas_equalTo(44);
//    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(titleView);
        make.centerY.equalTo(titleView);
        make.height.mas_equalTo(30);
    }];
    
    [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.areaLabel.mas_trailing).offset(5);
        make.height.mas_equalTo(11);
        make.width.mas_equalTo(14);
        make.centerY.equalTo(titleLabel.mas_centerY);
    }];
    arrowImageView.hidden = YES;
//    titleView.intrinsicContentSize = CGSizeMake(100, 44);
    
    self.navigationItem.titleView = titleView;
    
    self.levelBackgroundView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.levelBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    self.levelBackgroundView.hidden = YES;
    
    [self.view addSubview:self.levelBackgroundView];
    [self.levelBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    FZEnglishLevelSelectView *levelSelectView = [[FZEnglishLevelSelectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 6*45)];
    NSInteger levelIndex = 0;
    levelSelectView.currentLevel = levelIndex;
    
//    if (levelIndex >= 0 && levelIndex < [levelSelectView.items count]) {
//        NSString *leveName = levelSelectView.items[levelIndex];
//        self.areaLabel.text = leveName;
//    } else {
        self.areaLabel.text = @"我的班级";
//    }
    
    levelSelectView.didSelectBlock = ^(NSInteger selectedLevel, SRSchoolClassListModel *item) {
        weakSelf.areaLabel.text = item.name;
        [weakSelf didChangeClass:item];
    };
    
    [self.levelBackgroundView addSubview:levelSelectView];
    self.levelSelectView = levelSelectView;
    
    [self.levelSelectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.equalTo(self.levelBackgroundView);
        make.height.mas_equalTo(6*45);
    }];
    
    UIView *tapHideLevelView = [[UIView alloc] init];
    tapHideLevelView.backgroundColor = [UIColor clearColor];
    [tapHideLevelView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf hideLevelSelecteView];
    }];
    
    [self.levelBackgroundView addSubview:tapHideLevelView];
    [tapHideLevelView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.levelBackgroundView);
        make.top.equalTo(self.levelSelectView.mas_bottom);
        make.bottom.equalTo(self.levelBackgroundView);
    }];

}

- (void)setupNavigationItem {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 80, 26);
    [rightButton setTitle:@"添加作业" forState:UIControlStateNormal];
    rightButton.titleLabel.font = css.fontOfH5;
    
    self.rightButton = rightButton;
    [rightButton addTarget:self action:@selector(onRightButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    [self setRightBarButtonItem:rightItem];
    
    
//    UIButton *classDetailButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    classDetailButton.frame = CGRectMake(0, 0, 30, 26);
//    [classDetailButton setImage:[UIImage imageNamed:@"groupInformation"] forState:UIControlStateNormal];
//    [classDetailButton addTarget:self action:@selector(onClassDetailButton:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *classDetailItem = [[UIBarButtonItem alloc] initWithCustomView:classDetailButton];
//
//    self.classDetailButton = classDetailButton;
	
    FZDirectionButton *addClassButton = [FZDirectionButton buttonWithType:UIButtonTypeCustom];
    addClassButton.frame = CGRectMake(0, 0, 85, 26);
    [addClassButton setImage:[UIImage imageNamed:@"addmore"] forState:UIControlStateNormal];
	addClassButton.titleLabel.font = css.fontOfH5;
	
    [addClassButton addTarget:self action:@selector(onAddClassButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithCustomView:addClassButton];
	addClassButton.layoutDirection = FZDirectionButtonLayoutHorizontalImageLeft;
	
    self.addClassButton = addClassButton;
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                   target:nil action:nil];
    negativeSpacer.width = -5;//这个数值可以根据情况自由变化
    self.navigationItem.leftBarButtonItems = @[negativeSpacer, addItem];

    [self updateNaviButtonsHiddenStatus];
}

- (void)updateNaviButtonsHiddenStatus {
    if (self.userType == SRSchoolClassUserTypeTeacher) {
        self.classDetailButton.hidden = NO;
        self.addClassButton.hidden = NO;
        self.rightButton.hidden = NO;
        self.idtentySelectView.hidden = YES;
		[self.addClassButton setTitle:@"创建班级" forState:UIControlStateNormal];
    } else if (self.userType == SRSchoolClassUserTypeStudent) {
        self.classDetailButton.hidden = NO;
        self.addClassButton.hidden = NO;
        self.rightButton.hidden = YES;
        self.idtentySelectView.hidden = YES;
		[self.addClassButton setTitle:@"加入班级" forState:UIControlStateNormal];
    } else {
        self.classDetailButton.hidden = YES;
        self.addClassButton.hidden = YES;
        self.rightButton.hidden = YES;
    }
}

#pragma mark - Query Data

- (void)queryHomeworkDataFirst{
    self.pageIndex = 0;
    [self queryHomeworkData];
}

- (void)queryHomeworkData{
    WEAKSELF
    [SRSchoolClassServices queryWorkListPage:self.pageIndex groupID:self.groupID userType:self.userType successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf hideLoadingView];
        [weakSelf stopProgressHUD];
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            
            NSArray *addItems = @[];
            if ([responseDataObject isKindOfClass:[NSArray class]]) {
                addItems = responseDataObject;
            }
            
            if (weakSelf.pageIndex == 0) {
                [weakSelf.items removeAllObjects];
            }
            
            if ([addItems count] <= 0) {
                    //没有更多
                [weakSelf.tableView.footer noticeNoMoreData];
                if (weakSelf.pageIndex == 0) {
                    if (weakSelf.userType == SRSchoolClassUserTypeTeacher) {
                        [weakSelf emptyLoadingViewWithTitle:@"你还没有添加作业"];
                    } else {
                        [weakSelf emptyLoadingViewWithTitle:@"老师还没有布置作业"];
                    }
                }
                
            } else {
                weakSelf.pageIndex += [addItems count];
//                [weakSelf.items addObjectsFromArray:addItems];
                [weakSelf parseDataWithItems:addItems];
            }
            
            [weakSelf.tableView reloadData];
            
        } else {
            if (weakSelf.pageIndex == 0) {
                [weakSelf failedLoadingViewWithTitle:nil];
            }
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
        
        if ([weakSelf.items count] <= 0) {
            [weakSelf failedLoadingViewWithTitle:nil];
        }
        
    }];
    
}

- (void)queryClassListData{
    WEAKSELF
    
    [self.items removeAllObjects];
    
    [SRSchoolClassServices queryClassListUserType:self.userType successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf hideLoadingView];
//        [weakSelf.tableView.header endRefreshing];
//        [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            
            NSArray *addItems = @[];
            if ([responseDataObject isKindOfClass:[NSArray class]]) {
                addItems = responseDataObject;
            }
           
            if ([addItems count] <= 0) {
                    //没有更多
                weakSelf.classDetailButton.hidden = YES;
                weakSelf.addClassButton.hidden = YES;
                weakSelf.rightButton.hidden = YES;
                
//                [weakSelf.tableView.footer noticeNoMoreData];
                if (weakSelf.userType == SRSchoolClassUserTypeStudent) {
                    [weakSelf emptyLoadingViewWithTitle:@"你还没有加入班级"];
                    [weakSelf.loadingView.button setTitle:@"去添加" forState:UIControlStateNormal];
                    weakSelf.loadingView.buttonHidden = NO;
                    
                } else {
                    [weakSelf emptyLoadingViewWithTitle:@"你还没有创建班级"];
                    [weakSelf.loadingView.button setTitle:@"去创建" forState:UIControlStateNormal];
                    weakSelf.loadingView.buttonHidden = NO;
                }
                
            } else {
                weakSelf.classArray = addItems;
                weakSelf.classDetailButton.hidden = NO;
                weakSelf.addClassButton.hidden = NO;
                if ([weakSelf.classArray count] > 1) {
                    weakSelf.arrowImageView.hidden = NO;
                } else {
                    weakSelf.arrowImageView.hidden = YES;
                }
                
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                
                BOOL findLastClass = NO;
                NSString *lastClassID = [userDefaults objectForKey:kSRLastOpenClassID];
                if (lastClassID) {
                    for (SRSchoolClassListModel *model in weakSelf.classArray) {
                        NSString *classID = [NSString stringWithFormat:@"%@", model.identifiter];
                        if ([classID isEqualToString:lastClassID]) {
                            weakSelf.currentClassModel = model;
                            findLastClass = YES;
                            break;
                        }
                        
                    }
                }
                
                if (!findLastClass) {
                    weakSelf.currentClassModel = [addItems firstObject];
                }
                weakSelf.groupID = weakSelf.currentClassModel.identifiter;
                
                if (!lastClassID) {
                    lastClassID = [NSString stringWithFormat:@"%@", weakSelf.groupID];
                }
                [userDefaults setObject:lastClassID forKey:kSRLastOpenClassID];
                [userDefaults synchronize];
                
                weakSelf.areaLabel.text = weakSelf.currentClassModel.name;
                
                weakSelf.levelSelectView.items = weakSelf.classArray;
                weakSelf.levelSelectView.currentModel = weakSelf.currentClassModel;
                [weakSelf.levelSelectView reloadData];
				[weakSelf updateHeaderClassInfo];
                
                [weakSelf queryHomeworkDataFirst];
            }
            
                //
            
        } else {
            if (weakSelf.pageIndex == 0) {
                [weakSelf failedLoadingViewWithTitle:nil];
            }
            
            [weakSelf.tableView reloadData];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
        if ([weakSelf.classArray count] <= 0) {
            [weakSelf failedLoadingViewWithTitle:nil];
        }
        [weakSelf.tableView reloadData];

    }];
    
}

- (void)uploadUserSchoolTypeToServer:(SRSchoolClassUserType)userType {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:@(userType) forKey:@"user_type"];
    
    WEAKSELF
    
    [SRPersonalServices editUserInfo:params successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
//            [weakSelf showHUDHintWithText:@"修改身份成功"];
            if (responseDataObject) {
                [[SRLoginManager sharedManager] updateUserInfo:responseDataObject];
            }
            
            [weakSelf queryClassListData];
            
//            [[NSNotificationCenter defaultCenter] postNotificationName:kSRSchoolUserTypeDidChangeNotification object:nil];
            
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDErrorMessage:@"保存失败"];
    }];
}

#pragma mark - Event 

- (void)loginDidChangeNotification:(NSNotification *)notification {
    self.userType = [SRLoginUser schoolIdentity];
    [self updateNaviButtonsHiddenStatus];
    if (self.userType != SRSchoolClassUserTypeNone) {
        [self queryClassListData];
    }
}
- (void)schoolUserTypeDidChangeNotification:(NSNotification *)notification {
    self.userType = [SRLoginUser schoolIdentity];
    [self updateNaviButtonsHiddenStatus];
    [self queryClassListData];
}

- (void)createClassDidSuccessNotification:(NSNotification *)notification {
    [self updateNaviButtonsHiddenStatus];
    [self queryClassListData];
}

//kSRAddTaskDidSuccessNotification
- (void)AddTaskDidSuccessNotification:(NSNotification *)notification {
    [self queryHomeworkDataFirst];
}

    //kSRAddTaskDidSuccessNotification
- (void)AddClassDidSuccessNotification:(NSNotification *)notification {
    [self queryClassListData];
}


- (void)onTouchSelectIdenty:(BOOL)isTeaher {
    
    if (![SRLoginManager sharedManager].hasLogin) {
        [[SRLoginManager sharedManager] showLoginViewSinceController:self];
        return;
    }
    
    if (isTeaher) {
        SRAddToSchoolViewController *vc = [[SRAddToSchoolViewController alloc] initWithNibName:@"SRAddToSchoolViewController" bundle:nil];
        
        WEAKSELF
        vc.didChangeUserTypeBlock = ^{
            weakSelf.userType = SRSchoolClassUserTypeTeacher;
            
            [SRLoginUser setSchoolIdentity:weakSelf.userType];
            
            [weakSelf updateNaviButtonsHiddenStatus];
                //获取班级信息，显示班级作业
            [weakSelf uploadUserSchoolTypeToServer:weakSelf.userType];
        };
        
        [self pushViewController:vc animated:YES];
        
        return;
    }
    
    self.userType = isTeaher ? SRSchoolClassUserTypeTeacher : SRSchoolClassUserTypeStudent;
    
    [SRLoginUser setSchoolIdentity:self.userType];
    
    [self updateNaviButtonsHiddenStatus];
        //获取班级信息，显示班级作业
    [self uploadUserSchoolTypeToServer:self.userType];
    
//    [self queryClassListData];
    
}

- (void)onRightButton:(id)sender {
        //老师布置作业
    
//    SRGradeItemModel *item = [[SRGradeItemModel alloc] init];
//    item.gradeID = @"2";
//    item.grade = @"二年级";
//    
//    SRAlbumListViewController *vc = [[SRAlbumListViewController alloc] init];
//    vc.gradeModel = item;
    SRGradeListViewController *vc = [[SRGradeListViewController alloc] init];
    vc.isAddHomework = YES;
    vc.groupID = self.currentClassModel.identifiter;
    
    [self pushViewController:vc animated:YES];
}


- (void)onClassDetailButton:(id)sender {
    SRClassDetailViewController *vc = [[SRClassDetailViewController alloc] initWithNibName:@"SRClassDetailViewController" bundle:nil];
    vc.groupID = self.currentClassModel.identifiter;
    vc.userType = self.userType;
    
    [self pushViewController:vc animated:YES];
}


- (void)onAddClassButton:(id)sender {
    if (self.userType == SRSchoolClassUserTypeTeacher) {
            //创建班级
        [self showCreateClassVC];
    } else {
        [self showAddClassVC];
    }
}


    //先检查是否已经下载课本，若没有下载，则先下载。
- (IBAction)onDoHomeworkButton:(SRWorkListItemModel *)workModel {

    
    if (workModel.ctype == SRClassHomeworkTypePicture) {
            //看图题
        SRHomewokPictureViewController *vc = [[SRHomewokPictureViewController alloc] init];
        vc.taskID = workModel.task_id;
        vc.homeworkType = SRClassHomeworkTypePicture;
        
        [self pushViewController:vc animated:YES];
    } else if(workModel.ctype == SRClassHomeworkTypeRecord) {
        SRHomewokRecordViewController *vc = [[SRHomewokRecordViewController alloc] initWithNibName:@"SRHomewokRecordViewController" bundle:nil];
        vc.taskID = workModel.task_id;
        
        [self pushViewController:vc animated:YES];
        
    } else if(workModel.ctype == SRClassHomeworkTypeAudio) {
        SRHomeworkAudioViewController *vc = [[SRHomeworkAudioViewController alloc] init];
        vc.taskID = workModel.task_id;
        vc.homeworkType = SRClassHomeworkTypeAudio;
        
        [self pushViewController:vc animated:YES];
        
    } else if(workModel.ctype == SRClassHomeworkTypeDubbing) {
//    } else {
            //配音题
    if ([workModel.finishArray count] > 0) {
        SRWorkListItemModel *showModel = [workModel.finishArray firstObject];
        if (showModel.comment && [showModel.comment length] > 0) {
                //已点评，查看点评
            SRClassHomeworkStudentFinishViewController *vc = [[SRClassHomeworkStudentFinishViewController alloc] init];
            vc.detailModel = workModel;
            [self pushViewController:vc animated:YES];
        } else {
            
        }
        return;
    }
    
    NSString *bookID = [NSString stringWithFormat:@"%@", workModel.book_id];
    
    if ([[FZMCCacheManager defaultManager] isExistBookForBookID:bookID]) {
            //开始作业
        [self startDoHomeworkWithItem:workModel];

    } else {
        FZHomeCourseModel *item = [[FZHomeCourseModel alloc] init];
        item.identifier = workModel.book_id;
        item.title = workModel.name;
        item.pic = workModel.pic;
        item.zip = workModel.zip;
        
        [self updateHUDgrogress:MBProgressHUDModeDeterminate labelText:@"正在下载..."];
        WEAKSELF
        item.successBlock = ^(NSURLRequest * _Nullable request, NSHTTPURLResponse * _Nullable response, NSURL * _Nonnull originURL, NSString * _Nonnull localFilePath) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDErrorMessage: @"下载完成"];
            
            [weakSelf startDoHomeworkWithItem:workModel];
            
        };
        
        item.progressBlock = ^(NSProgress * _Nonnull progress, MCDownloadReceipt * _Nonnull receipt) {
            
            if (receipt.state == MCDownloadStateDownloading) {
                [weakSelf updateMyProgressTask:progress.fractionCompleted];
                
//                weakSelf.progressView.progress = progress.fractionCompleted;
//                NSString *progressString = [NSString stringWithFormat:@"%d%%", (int)(progress.fractionCompleted * 100)];
//                weakSelf.progressLabel.text = progressString;
            } else if (item.downloadState == MCDownloadStateSuspened || item.downloadState == MCDownloadStateWillResume) {
//                weakSelf.progressView.progress = progress.fractionCompleted;
                
            }
        };
        
        item.failureBlock = ^(NSURLRequest * _Nullable request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDErrorMessage: @"下载失败"];

        };

        
        [[FZMCCacheManager defaultManager] addBook:item];
        [[FZMCCacheManager defaultManager] startDownloadBook:item];
        
        [SRSpeakingDatabaseManager saveBookModel:item];
        
        
    }
    }
}

- (void)startDoHomeworkWithItem:(SRWorkListItemModel *)workModel{
//CatalogueID:(NSString *)catalogueID bookID:(NSString *)bookID {
    SRBookRootModel *bookModel = [[FZMCCacheManager defaultManager] readBookModelFromDocumentWithBookID:workModel.book_id];
    NSString *catalogueID = workModel.catalogue_id;
    
    if (bookModel) {
            //给page添加单元id catalogue_id
        NSArray *catalogueArray = bookModel.catalogues;
        NSArray *pagesArray = bookModel.pages;
        
        for (int i = 0; i < [catalogueArray count]; ++ i) {
            SRBookCatalogueModel *catalogueModel = [catalogueArray objectAtIndex:i];
            for (int j = 0; j < [pagesArray count]; ++ j) {
                SRBookPageModel *pageModel = pagesArray[j];
                NSArray *cataPageIDs = [catalogueModel.page_id splitWith:@","];
                if ([cataPageIDs containsObject:pageModel.pageID]) {
                    pageModel.catalogue_id = catalogueModel.catalogue_id;
                }
            }
        }
    } else {
        [self showHUDErrorMessage:@"课本解析失败"];
        return;
    }
    
    NSString *currentCatalogueID = catalogueID;
    SRBookCatalogueModel *currentCatalogueModel = nil;
    for (SRBookCatalogueModel *catalogueModel in bookModel.catalogues) {
        if ([catalogueModel.catalogue_id isEqualToString:currentCatalogueID]) {
            currentCatalogueModel = catalogueModel;
            break;
        }
    }
    
    NSMutableArray *trackArray = [@[] mutableCopy];
    for (int j = 0; j < [bookModel.pages count]; ++ j) {
        SRBookPageModel *pageModel = bookModel.pages[j];
        if ([pageModel.catalogue_id isEqualToString:currentCatalogueID] && [pageModel.tracks count] > 0){
            [trackArray addObjectsFromArray:pageModel.tracks];
        }
    }
    
    SRSpeakingTestViewController *vc = [[SRSpeakingTestViewController alloc] init];
    vc.items = trackArray;//self.currentPageModel.tracks;
    vc.catalogueModel = currentCatalogueModel;
    vc.bookID = bookModel.bookID;
    vc.bookName = bookModel.name;
    vc.groupID = self.currentClassModel.identifiter;
    vc.taskID = workModel.task_id;
    [self pushViewController:vc animated:YES];
}


- (void)touchDeleteButtonAction:(SRWorkListItemModel *)item {
    self.selectedModel = item;
    UIAlertView * alterView=[[UIAlertView alloc] initWithTitle:@"删除确认" message:@"是否删除已发布的任务，如果删除学生将不能查看本任务？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alterView.tag = 1000;
    [alterView show];
}

- (void)deleteWorkWithModel:(SRWorkListItemModel *)item {
    
    NSString *taskID = [NSString stringWithFormat:@"%@", item.task_id];
    [self.items removeObject:item];

    WEAKSELF
    [SRSchoolClassServices deleteTaskGroupID:self.currentClassModel.identifiter taskID:taskID successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDErrorMessage:@"删除成功"];
            
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
        [weakSelf.tableView reloadData];

    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf showHUDErrorMessage:@"删除失败"];
        [weakSelf.tableView reloadData];

    }];
    

}

- (IBAction)onShowMemberListButton:(id)sender {
	
	SRClassMemberListViewController *vc = [[SRClassMemberListViewController alloc] init];
	vc.userType = self.userType;
	vc.classModel = self.currentClassModel;
	
//	WEAKSELF
//	vc.DeleteStudentSuccessBlock = ^(NSArray *uids) {
//
////		STRONGSELFFor(weakSelf)
////		[strongSelf queryData];
//	};
	
	[self pushViewController:vc animated:YES];
	
}


#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self deleteWorkWithModel:self.selectedModel];
    }
}

#pragma mark - Private Show

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:animated];
}


    //切换等级
- (void)onleftChangeLevelButton:(UIButton *)button {
    
    if (self.userType == SRSchoolClassUserTypeNone || [self.classArray count] <= 1) {
        return;
    }
    
    if (self.levelBackgroundView.hidden) {
        self.levelBackgroundView.hidden = NO;
        
        [self.levelSelectView reloadData];
        [self.view bringSubviewToFront:self.levelBackgroundView];
    } else {
        self.levelBackgroundView.hidden = YES;
    }
}



- (void)didChangeClass:(SRSchoolClassListModel *)item {
    self.levelBackgroundView.hidden = YES;
    
    self.currentClassModel = item;
    self.groupID = self.currentClassModel.identifiter;
    NSString *lastClassID = [NSString stringWithFormat:@"%@", self.groupID];
    [[NSUserDefaults standardUserDefaults] setObject:lastClassID forKey:kSRLastOpenClassID];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self updateHeaderClassInfo];
    
    self.pageIndex = 0;
    
    [self startProgressHUD];
    
    [self queryHomeworkDataFirst];
}

- (void)hideLevelSelecteView {
    self.levelBackgroundView.hidden = YES;
}


    //添加班级
- (void)showAddClassVC {
    SRAddClassViewController *vc = [[SRAddClassViewController alloc] initWithNibName:@"SRAddClassViewController" bundle:nil];
    [self pushViewController:vc animated:YES];
    
}

- (void)showCreateClassVC {
    SRCreateClassViewController *vc = [[SRCreateClassViewController alloc] initWithNibName:@"SRCreateClassViewController" bundle:nil];
    
    [self pushViewController:vc animated:YES];
}

- (void)updateHeaderClassInfo{
	[self.infoHeaderView updateHeaderInfo:self.currentClassModel];
}

#pragma mark - section Handle 

- (void)parseDataWithItems:(NSArray *)addItems {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"MM月dd日";
    
    for (SRWorkListItemModel *model in addItems) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[model.create_time longLongValue]];
        NSString *dateString = [df stringFromDate:date];
        
        model.displayTimeString = dateString;
    }
    
    if ([addItems count] > 0) {
        [self.items addObjectsFromArray:addItems];
        
        [self updateSectionItem];
    }
}

-(void)updateSectionItem{
    [self.sectionArray removeAllObjects];
    
    NSString *otherGroupTag = @"#";
    BOOL shouldShowOtherTag = NO;
    for (SRWorkListItemModel *model in self.items) {
        if (model.displayTimeString) {
            [self.sectionArray addObject:model.displayTimeString];
        } else {
            shouldShowOtherTag = YES;
        }
    }
    
    NSMutableArray* sortArray = [[self.sectionArray valueForKeyPath:@"@distinctUnionOfObjects.self"] mutableCopy];
        //    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
        //    NSArray *tempArr = [sectionForArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
    
    [sortArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *item1 = obj1;
        NSString *item2 = obj2;
        NSComparisonResult result = [item2 compare:item1];
        return result;
            //        if (result == NSOrderedAscending) {
            //            return NSOrderedAscending;
            //        }
    }];
    
    NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:5];
    if ([sortArray count] > 0) {
        [sectionArray addObjectsFromArray:sortArray];
    }
    if (shouldShowOtherTag) {
        [sectionArray addObject:otherGroupTag];//
    }
    
    
    self.sectionArray =  sectionArray;
}

-(NSMutableArray* )findForKeyString:(NSString*)KeyString value:(NSString*)keyValue inArray:(NSArray*)dataForarray
{
    NSMutableArray* dataMutableArray =[[NSMutableArray alloc] initWithCapacity:2];
    for (SRWorkListItemModel * modelData in dataForarray) {
        if (modelData) {
            NSString *value = [modelData valueForKey:KeyString];
            if ([value isEqualToString:keyValue]) {
                [dataMutableArray addObject:modelData];
            }
            else  if ([keyValue isEqualToString:@"#"] && (!value || [value isEqualToString:@""] || [@"#" isEqualToString:[modelData valueForKey:KeyString]])) {
                [dataMutableArray addObject:modelData];
            }
        }
    }
    
    return dataMutableArray;
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sectionName = [self.sectionArray objectAtIndex:section];
    NSMutableArray* dataArray = [self findForKeyString:kAlbumSectionDefineKey value:sectionName inArray:self.items];
    return dataArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRClassHomeworkListTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRClassHomeworkListTableViewCell forIndexPath:indexPath];
    cell.userType = self.userType;
    cell.isEditStatus = self.isEditStatus;

    NSString* sectionName = [self.sectionArray objectAtIndex:indexPath.section];
    NSArray *dataArray = [self findForKeyString:kAlbumSectionDefineKey value:sectionName inArray:self.items];
    if ([dataArray count] > indexPath.row) {
        SRWorkListItemModel *item = dataArray[indexPath.row];
        [cell updateCellInfo:item];
        
    }
    
    WEAKSELF
    cell.touchDoHomeworkButtonBlock = ^(SRWorkListItemModel *item) {
        if (weakSelf.userType == SRSchoolClassUserTypeStudent) {
            [weakSelf onDoHomeworkButton:item];
        }
    };
    
    cell.touchDeleteButtonBlock = ^(SRWorkListItemModel *item) {
        [weakSelf touchDeleteButtonAction:item];
    };
    
    
    return cell;
}


#pragma mark - UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.userType == SRSchoolClassUserTypeTeacher) {
        if (self.isEditStatus) {
            NSString* sectionName = [self.sectionArray objectAtIndex:indexPath.section];
            NSArray *dataArray = [self findForKeyString:kAlbumSectionDefineKey value:sectionName inArray:self.items];
            if ([dataArray count] > indexPath.row) {
                SRWorkListItemModel *item = dataArray[indexPath.row];
                [self touchDeleteButtonAction:item];
            }
        } else {
            
            NSString* sectionName = [self.sectionArray objectAtIndex:indexPath.section];
            NSArray *dataArray = [self findForKeyString:kAlbumSectionDefineKey value:sectionName inArray:self.items];
            if ([dataArray count] > indexPath.row) {
                SRWorkListItemModel *item = dataArray[indexPath.row];
                SRClassHomeWorkDetailViewController *vc = [[SRClassHomeWorkDetailViewController alloc] init];
                vc.userType = self.userType;
                vc.detailModel = item;
                vc.homeworkType = item.ctype;
                
                [self pushViewController:vc animated:YES];
            }
        }
    } else {
            //学生
        NSString* sectionName = [self.sectionArray objectAtIndex:indexPath.section];
        NSArray *dataArray = [self findForKeyString:kAlbumSectionDefineKey value:sectionName inArray:self.items];
        if ([dataArray count] > indexPath.row) {
            SRWorkListItemModel *item = dataArray[indexPath.row];
            if (item.ctype != SRClassHomeworkTypeRecord && [item.finishArray count] > 0) {
                SRWorkListItemModel *showModel = [item.finishArray firstObject];
                if (showModel.comment && [showModel.comment length] > 0) {
                        //已点评，查看点评
                    SRClassHomeworkStudentFinishViewController *vc = [[SRClassHomeworkStudentFinishViewController alloc] init];
                    vc.detailModel = item;
                    [self pushViewController:vc animated:YES];
                } else {
                    
                }
                return;
            } else {
                [self onDoHomeworkButton:item];
            }
           
        }
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45.f;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SRBookCatalogueSectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kSRBookCatalogueSectionHeaderView];
    sectionHeaderView.leftViewHidden = NO;
    sectionHeaderView.backgroundView.backgroundColor = [FZStyleSheet currentStyleSheet].color_2;
    sectionHeaderView.moreHidden = NO;
    sectionHeaderView.titleLabel.font = [UIFont systemFontOfSize:15];
    
    NSString* sectionName = [self.sectionArray objectAtIndex:section];
    sectionHeaderView.titleLabel.text =  [NSString stringWithFormat:@"任务：%@", sectionName];
    if (self.isEditStatus) {
        [sectionHeaderView.moreButton setTitle:@"取消" forState:UIControlStateNormal];
    }
    else {
        [sectionHeaderView.moreButton setTitle:@"任务管理" forState:UIControlStateNormal];
    }
    WEAKSELF
    sectionHeaderView.touchMoreButtonBlock = ^(id sender) {
        weakSelf.isEditStatus = !weakSelf.isEditStatus;
        [weakSelf.tableView reloadData];
    };
    
    
    return sectionHeaderView;
}

@end
